<?php 
require_once eCMS_DIR . '/module/user/Newsletter/model/NewsletterModel.class.php';


class Newsletter extends Page {
	
	function __construct($pkPage) {
		parent::__construct($pkPage);
	}
	
	protected function loadSecurityObjects() {

		parent::loadSecurityObjects();
	
	}
	
	protected function addPageMethods() {
		
		parent::addPageMethods();	
		
		if($this->canInstanceRead()) {
			$this->allowMethod("addSubscription");
		}
		if($this->canInstanceUpdate()) {
			$this->allowMethod("edit");
            $this->allowMethod("export", "admin");
            $this->allowMethod("delete", "admin");
        }
		
		$this->allowMethod("export", "admin");		
		
				
	}
	
	public function index() {
		
	}
	
	public function edit() {
		
		$this->addToolboxItem(new ToolBoxItem("Liste herunterladen", "sheet.png", $this->getUrl()."&method=export"),"instance");
				
		
		$l = new NewsletterSubscriptionList();
		$list = $l->GetByFkModuleInstance($this->fkModuleInstance);
		
		$this->addViewData("List", $list);
		
	}
	
	public function export() {
		
		$l = new NewsletterSubscriptionList();
		$list = $l->GetByFkModuleInstance($this->fkModuleInstance);
		
		$this->addViewData("List", $list);
		
		$this->setAjaxResponse();
		
		header("Content-type: application/vnd.ms-excel");
  		header("Content-disposition: attachment; filename=newsletter-export-" . date("Y-m-d") . ".csv");
		
	}

    public function delete() {

        $pk = $this->pageRequest->getGetVar("pkNewsletterSubscription");

        if($pk) {

            $list = new NewsletterSubscriptionList();
            $list->GetByPkNewsletterSubscription($pk);
            $entry = $list->At(0);

            if($entry->delete()) {
                $this->logEvent("DeletedNewsletterSubscription", __FILE__, __CLASS__, __FUNCTION__, __LINE__);
            }

        }

        Utils::jsRedirect($this->getUrl() . "&method=edit");

    }
	
	public function addSubscription() {
		
			$cfg = Runtime::getConfiguration();
			/*
			$t = new TableAdapter($cfg['table_prefix']."ModNewsletterSubscription");
			$t->enableDebug();
			if($t->updateInsert($_GET, null, "Newsletter", array("fkModuleInstance"=>$this->fkModuleInstance, "regID"=>"'" . md5(rand()) . "'" ))) {
			*/
			
			$entry = new NewsletterSubscriptionItem();
			DataMapper::Map($this->pageRequest->getGetArray(), $entry, "Newsletter");
			$entry->fkModuleInstance = $this->fkModuleInstance;
			$entry->source = "Website";
				
			if($entry->save()) {
				$this->logEvent("AddSubscription", __FILE__, __CLASS__, __FUNCTION__, __LINE__);
				$this->setJsonResponse("ok");
			}
			else {
				$this->logEvent("AddSubscriptionFailed", __FILE__, __CLASS__, __FUNCTION__, __LINE__);
				$this->setJsonResponse("failure");
			}
			
			$this->isPlainText = true;
	}
	
}

?>